<template>
  <div class="rating-config">
    <el-card>
      <div slot="header">
        <div class="header-operation">
          <span>结算比例配置管理</span>
          <el-button type="primary" @click="handleAdd">新增配置</el-button>
        </div>
      </div>
      
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="ratingStar" label="星级" align="center"></el-table-column>
        <el-table-column prop="ratingCommission" label="抽佣比例" align="center">
          <template slot-scope="scope">{{ Math.round(scope.row.ratingCommission) }}%</template>
        </el-table-column>
        <el-table-column prop="ratingDesc" label="备注" align="center"></el-table-column>
        <el-table-column prop="creator" label="创建人" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" danger @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-card>
    
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="星级" prop="ratingStar">
          <el-input v-model.number="form.ratingStar" placeholder="请输入星级（1-5）"></el-input>
        </el-form-item>
        <el-form-item label="抽佣比例" prop="ratingCommission">
          <el-input 
            v-model.number="form.ratingCommission" 
            placeholder="请输入抽佣比例（如70代表70%）"
            oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/^0+(\d)/, '$1')"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="ratingDesc">
          <el-input v-model="form.ratingDesc" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from "@/http/adminApi";

export default {
  data() {
    return {
      tableData: [],
      tenantId: 1,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: "新增结算比例",
      form: {
        id: null,
        ratingStar: null,
        ratingCommission: null,
        ratingDesc: ""
      },
      rules: {
        ratingStar: [
          { required: true, message: "请输入星级", trigger: "blur" },
          { type: "number", min: 1, max: 5, message: "星级必须在1-5之间", trigger: "blur" }
        ],
        ratingCommission: [
          { required: true, message: "请输入抽佣比例", trigger: "blur" },
          { type: "number", min: 0, max: 100, message: "抽佣比例必须在0-100之间", trigger: "blur" },
          { validator: this.checkInteger, message: "抽佣比例必须为整数", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    checkInteger(rule, value, callback) {
      if (value !== null && value !== undefined && !Number.isInteger(value)) {
        callback(new Error("抽佣比例必须为整数"));
      } else {
        callback();
      }
    },
    loadData() {
      adminApi.getRatingList({
        tenantId: this.tenantId,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list.map(item => ({
            ...item,
            ratingCommission: Math.round(item.ratingCommission * 100)
          }));
          this.total = res.data.total;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    handleAdd() {
      this.dialogTitle = "新增结算比例";
      this.form = {
        id: null,
        ratingStar: null,
        ratingCommission: null,
        ratingDesc: ""
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑结算比例";
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(id) {
      this.$confirm("确定要删除这条配置吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        adminApi.deleteRating({ id }).then(res => {
          // 统一接口响应判断逻辑（与新增/编辑保持一致）
          if (res.code === 200 || res.success) {
            this.$message.success("删除成功");
            this.loadData(); // 删除后刷新数据
          } else {
            this.$message.error("删除失败：" + (res.msg || "未知错误"));
          }
        }).catch(() => {
          this.$message.error("删除接口请求失败");
        });
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            ratingCommission: this.form.ratingCommission / 100
          };

          if (this.form.id) {
            // 编辑操作
            adminApi.updateRating(submitData).then(res => {
              if (res.code === 200 || res.success) {
                this.$message.success("更新成功");
                this.dialogVisible = false; // 关闭弹窗
                this.loadData(); // 刷新数据
              } else {
                this.$message.error("更新失败：" + (res.msg || "未知错误"));
              }
            }).catch(() => {
              this.$message.error("更新接口请求失败");
            });
          } else {
            // 新增操作
            adminApi.addRating(submitData).then(res => {
              if (res.code === 200 || res.success) {
                this.$message.success("新增成功");
                this.dialogVisible = false; // 关闭弹窗
                this.loadData(); // 刷新数据
              } else {
                this.$message.error("新增失败：" + (res.msg || "未知错误"));
              }
            }).catch(() => {
              this.$message.error("新增接口请求失败");
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.header-operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>